package com.open.capacity.common.controller;

import com.open.capacity.commons.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;


/**
 * @author huangtiande@rfchina.com create_date: 2018-8-21
 */
@RestControllerAdvice
@Slf4j
public class ErrorController {

    @ExceptionHandler(value = Exception.class)
    public Result handleException(Exception ex) {
        log.error(getExceptionInfo(ex));
        String errorMsg = ex.getMessage();
        return Result.failed(errorMsg);
    }

    private static String getExceptionInfo(Exception e) {
        StackTraceElement[] stackTrace = e.getStackTrace();
        StringBuffer sb = new StringBuffer();
        sb.append(e.toString()).append("\r\n");
        for (StackTraceElement stackTraceElement : stackTrace) {
            sb.append("\tat ").append(stackTraceElement.getClassName()).append(".")
                    .append(stackTraceElement.getMethodName())
                    .append("(").append(stackTraceElement.getFileName()).append(":").append(stackTraceElement.getLineNumber())
                    .append(")\r\n");
        }
        return sb.toString();

    }

}
